/**
 * Copyright (c) 2005 - 2007 FeyaSoft Corp. All Rights Reserved.
 */
package com.feyaSoft.home.web.demouser;

import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.web.servlet.ModelAndView;

import com.feyaSoft.home.dao.base.BaseSearchResult;
import com.feyaSoft.home.hibernate.demouser.Demouser;
import com.feyaSoft.home.services.demouser.DemouserServiceImpl;
import com.feyaSoft.home.services.demouser.ListDemouserInfo;
import com.feyaSoft.home.web.base.BaseController;
import com.feyaSoft.home.web.common.JsonMVCUtil;
import com.feyaSoft.plugin.util.JsonUtil;

/**
 * @author Fenqiang Zhuang
 * @Oct 5, 2007
 * 
 * This file is used to .....
 */
public class DemouserController extends BaseController {
	// log file
	private final static Logger log = Logger
			.getLogger(DemouserController.class);
	private DemouserServiceImpl demouserService;
	private String LIST_INFO = "listDemouserInfo";

	/**
	 * Call by Ajax - here we need create a json object..
	 * 
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	public ModelAndView listResult(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		HttpSession session = request.getSession();

		// check session expired...
		ListDemouserInfo listDemouserInfo = new ListDemouserInfo();
		if (session.getAttribute(LIST_INFO) != null) {
			listDemouserInfo = (ListDemouserInfo) session
					.getAttribute(LIST_INFO);
		}

		// get paging information now...start paging
		if (request.getParameter("start") != null) {
			int start = Integer.parseInt((String) request.getParameter("start")
					.trim());
			double floatPageNum = start / 10;
			int intPageNum = (int) Math.ceil(floatPageNum);
			listDemouserInfo.setCurrentPage(intPageNum + 1);
			session.setAttribute(LIST_INFO, listDemouserInfo);
		}

		// call update and delete ....
		if (request.getParameter("delData") != null) {
			// user want to archive those type...
			String jsonString = request.getParameter("delData");
			deleteAccounts(jsonString);
		}

		// call service to get result
		BaseSearchResult searchResult = demouserService
				.getList(listDemouserInfo);

		// create json object and return back ...call DB get latest information
		// create JSON response
		DemouserUtil.jsonResponse(searchResult, request, response);

		return null;
	}

	/**
	 * load data by id now. And return JSON data result to response
	 * 
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	public ModelAndView loadData(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		// get id first
		String userId = (String) request.getParameter("id").trim();
		Demouser demouser = demouserService.getDemouserById(new Long(userId));

		// push data back to Ajax page
		JsonMVCUtil.jsonFormalResponse(demouser.toJSONObject(), request,
				response);

		return null;
	}

	/**
	 * create health
	 * 
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	public ModelAndView createDemouser(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		Demouser demouser = DemouserUtil.setDemouser(request, demouserService);
		JSONObject errors = new JSONObject();

		try {
			// now start to check whether username already in use
			// - server side validation
			Demouser existedUser = demouserService
					.loadDemouserByUsername(demouser.getUsername());
			if (existedUser != null) {
				errors.put("id", "username");
				errors.put("msg",
						"This username also in use, please select another one");
				JsonMVCUtil.jsonErrorsResponse(errors, request, response);
				return null;
			}

			demouser.setCreationDate(new Date());
			demouser.setUpdateDate(new Date());
			demouserService.saveDemouser(demouser);
			JsonMVCUtil.jsonOkResponse(
					"You have successfully created this accout", request,
					response);

		} catch (Exception e) {
			log.error("saveDemouser failed");
			JsonMVCUtil.jsonFailResponse("Internal Error, please try again",
					request, response);
		}

		return null;
	}
	
	/**
	 * Edit user now
	 * 
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	public ModelAndView editDemouser(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		Demouser demouser = DemouserUtil.setDemouser(request, demouserService);

		try {
			demouserService.saveDemouser(demouser);
			JsonMVCUtil.jsonOkResponse(
					"You have successfully updated this accout", request,
					response);
		} catch (Exception e) {
			JsonMVCUtil.jsonFailResponse("Internal Error, please try again",
					request, response);
		}

		return null;
	}

	/**
	 * client click delete account in here
	 * 
	 * @param jsonString
	 * @throws Exception
	 */
	private void deleteAccounts(String jsonString) throws Exception {
		JSONArray jsonArray = JsonUtil.getJsonArray(jsonString);

		// loop through - get from json and update
		for (int i = 0; i < jsonArray.length(); i++) {
			JSONObject jsonObject = jsonArray.getJSONObject(i);
			String id = jsonObject.getString("id");
			demouserService.deleteDemouser(new Long(id));
		}
	}

	// spring inject
	public void setDemouserService(DemouserServiceImpl demouserService) {
		this.demouserService = demouserService;
	}

}
